package com.jdz.gxq.info.common.taglib;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.TagSupport;

import jp.terasoluna.fw.util.PropertyUtil;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.taglib.TagUtils;

import com.jdz.gxq.info.common.bo.PageBean;

public class PagerTag extends TagSupport {

	private static final long serialVersionUID = 1L;
	
	private static Log logger = LogFactory.getLog(PagerTag.class);
	
	private static String ERROR_MESSAGE_FORMID_REQUIRED = "formid attribute is required.";
	
	private static String PAGE_LINKS_FIRST_CHAR = "pageLinks.first.char";
	
	private static String PAGE_LINKS_PREV_CHAR = "pageLinks.prev.char";
	
	private static String PAGE_LINKS_NEXT_CHAR = "pageLinks.next.char";
	
	private static String PAGE_LINKS_END_CHAR = "pageLinks.end.char";
	
	private static String PAGE_LINKS_GO_CHAR = "pageLinks.go.char";

	/**
	 * 提交form的id
	 */
	private String formId;
	
	private String indexProperty;
	
	/**
	 * 分页信息放置的key
	 */
	private String pageBeanName = "pageBean";

	/**
	 * 数据存放范围
	 */
	protected String scope = "request";
	
	public String getPageBeanName() {
		return pageBeanName;
	}

	public void setPageBeanName(String pageBeanName) {
		this.pageBeanName = pageBeanName;
	}

	public String getScope() {
		return scope;
	}

	public void setScope(String scope) {
		this.scope = scope;
	}

	public String getFormId() {
		return formId;
	}

	public void setFormId(String formId) {
		this.formId = formId;
	}

	public String getIndexProperty() {
		return indexProperty;
	}

	public void setIndexProperty(String indexProperty) {
		this.indexProperty = indexProperty;
	}

	public int doStartTag() throws JspException {
		
		// 参数校验
		if ((formId == null || "".equals(formId))) {
            logger.error(ERROR_MESSAGE_FORMID_REQUIRED);
            throw new JspException(ERROR_MESSAGE_FORMID_REQUIRED);
        }
		
		PageBean pageBean = (PageBean) lookup(pageContext, "", pageBeanName, scope);;
		
		// 指定输入流，用于页面输出分页信息
		JspWriter out = pageContext.getOut();

		// 构建StringBuffer对象，用户拼接分页标签
		StringBuilder sb = new StringBuilder();

		defineHtml();
		
		createPageInfo(sb, pageBean);
		
		try {
			out.println(sb.toString());
		} catch (IOException e) {
			logger.error(e.getMessage());
			throw new JspException(ERROR_MESSAGE_FORMID_REQUIRED);
		}
		
		return SKIP_BODY;
	}
	
	private void createPageInfo(StringBuilder sb, PageBean pageBean) throws JspException {
	
		// 显示当前页和总页数
		sb.append("<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">");
		sb.append("<tr>");
		
		sb.append("<td class=\"STYLE4\" align=\"left\">");
		sb.append("&nbsp;&nbsp;");
		sb.append("共有&nbsp;").append(pageBean.getTotalCount()).append("&nbsp;记录，");
		sb.append("当前第&nbsp;").append(pageBean.getCurrentPage()).append("/").append(pageBean.getTotalPageCount()).append("&nbsp;页");
		sb.append("</td>");
		
		sb.append("<td class=\"STYLE4\" align=\"right\">");
		addFirstSubmit(sb, pageBean);
		addPrevSubmit(sb, pageBean);
		addNextSubmit(sb, pageBean);
		addEndSubmit(sb, pageBean);
		addChangeSubmit(sb);
		sb.append("</td>");
		
		sb.append("</tr>");
		sb.append("</table>");
	}
	
	private void addFirstSubmit(StringBuilder sb, PageBean pageBean) {
		
		String firstChar = PropertyUtil.getProperty(PAGE_LINKS_FIRST_CHAR);

		if (pageBean.getCurrentPage() == 1) {
			sb.append(firstChar);
		} else {

			sb.append("<a href=\"#\" onclick=\"pageLinkSubmit(1)\">");
			sb.append(firstChar);
			sb.append("</a>");
		}
		sb.append("&nbsp;");
	}
	
	private void addPrevSubmit(StringBuilder sb, PageBean pageBean) {
		
		String prevChar = PropertyUtil.getProperty(PAGE_LINKS_PREV_CHAR);
		
		if (pageBean.isHasPrevious()) {
			sb.append("<a href=\"#\" onclick=\"pageLinkSubmit(" + pageBean.getPreviousPage() + ")\">");
			sb.append(prevChar);
			sb.append("</a>");
		} else {
			sb.append(prevChar);
		}
		sb.append("&nbsp;");
	}
	
	private void addNextSubmit(StringBuilder sb, PageBean pageBean) {
		
		String nextChar = PropertyUtil.getProperty(PAGE_LINKS_NEXT_CHAR);
		
		if (pageBean.isHasNext()) {
			sb.append("<a href=\"#\" onclick=\"pageLinkSubmit(" + pageBean.getNextPage() + ")\">");
			sb.append(nextChar);
			sb.append("</a>");
		} else {
			sb.append(nextChar);
		}
		sb.append("&nbsp;");
	}
	
	private void addEndSubmit(StringBuilder sb, PageBean pageBean) {
		
		String endChar = PropertyUtil.getProperty(PAGE_LINKS_END_CHAR);
		
		if (pageBean.isHasNext()) {
			sb.append("<a href=\"#\" onclick=\"pageLinkSubmit(" + pageBean.getTotalPageCount() + ")\">");
			sb.append(endChar);
			sb.append("</a>");
		} else {
			sb.append(endChar);
		}
		sb.append("&nbsp;");
	}
	
	private void addChangeSubmit(StringBuilder sb) {
		
		String goChar = PropertyUtil.getProperty(PAGE_LINKS_GO_CHAR);
		
		sb.append("转到第&nbsp;");  
		sb.append("<input type=\"text\" name=\"pageText\" id=\"pageText\" style=\"height:20px; width:25px; border:1px solid #999999;\"/>");
		sb.append("&nbsp;页&nbsp;");
		sb.append("<a href=\"#\" onclick=\"pageLinkSubmit(document.getElementById('pageText').value)\">");
		sb.append(goChar);
		sb.append("</a>");
	}
	;
	private void defineHtml() throws JspException {
		
		JspWriter writer = pageContext.getOut();
		
		try {

			// 生成提交表单的JS
			writer.print("<script type=\"text/javascript\">");
			writer.println("  function pageLinkSubmit(pageIndex) {");
			writer.print("    document.forms[\"" + formId + "\"]");
			writer.append(".");
			writer.append(indexProperty);
			writer.append(".value=pageIndex;");
			writer.print("    document.forms[\"" + formId + "\"]");
			writer.println(".submit();");

			writer.println("  }");
			writer.print("</script>");
			
		} catch (IOException e) {
			
			logger.error(e.getMessage());
			throw new JspTagException(e.toString());
		}
	}
	
	private Object lookup(PageContext pageContext, String name, 
            String property, String scope) throws JspException{
        if (property == null || "".equals(property)) {
            return null;
        }
        Object retObj = null;
        if (name != null && !"".equals(name)) {
            retObj = TagUtils.getInstance().lookup(pageContext, name,
                    property, scope);
        } else {
            retObj = TagUtils.getInstance().lookup(pageContext,
                    property, scope);
        }
        return retObj;
    }

}
